 /* Copyright (C)
  * 2024 ZKLX Optoelectronic Technology Co.LTD
  * All rights reserved.
  */
 /**
  * @file lx_serial.h
  * @brief 串口通信接口头文件
  * @author xuke
  * @version 1.0
  * @date 2024-04-19
  */

#ifndef _LX_SERIAL_H_
#define _LX_SERIAL_H_

/*------------------Include Files----------------------------*/
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <cstdio>
#include <map>
#include <mutex>
/*------------------End of Include Files---------------------*/

/*------------------Macro Definition-------------------------*/
/*------------------End of Macro Definition------------------*/

/*------------------Typedefs Definition----------------------*/
class serial {
	public:
		// 波特率映射表
		const std::map<int, int> baudMap = {
			{921600, B921600},
			{115200, B115200},
			{38400,  B38400},
			{19200,  B19200},
			{9600,   B9600},
			{4800,   B4800},
			{2400,   B2400},
			{1200,   B1200},
			{300,    B300}
		};
		// 校验模式
		enum parityEnum {
			PARITY_MARK = 1,     // 1校验
			PARITY_SPACE = 0,    // 0校验
			PARITY_ODD = 2,      // 奇校验
			PARITY_EVEN = 3,     // 偶校验
			PARITY_NONE = 4      // 无校验
		};
		// 类中的真假值
		static const int TRUE = 0;
		static const int FALSE = -1;

		//方法接口
		explicit serial(const std::string portadd);
		serial(const std::string portadd, int baud, int databits, int stopbits = 1, parityEnum parity = PARITY_NONE);
		~serial();
		int open();
		void close();
		int setReadTimeout(int timeout);
		int send(const unsigned char *sendBuf, const int sendBytes);
		int duplexPairs(const unsigned char *sendBuf, unsigned char *recvBuf, const int sendBytes, const int recvBytes, const int timeout = 20);

		int speed;           // 波特率设置
	private:
		int fd;              // 文件句柄
		int databits;        // 数据位设置
		int stopbits;        // 停止位设置
		int readTimeout;     // 超时设置(100us)
		bool isOpen;         // 串口打开/关闭标志位
		std::string portadd; // 端口地址
		parityEnum parity;   // 校验位设置
		std::mutex useMutex; // 串口在用互斥量

		int setSpeed();
		int setParity();
};
/*------------------End of Typedefs Definition---------------*/

/*------------------API Definition---------------------------*/
/*------------------End of API Definition--------------------*/

#endif /* End of _LX_SERIAL_H_ */

